// unit testing, lpr (license plate recognition)

#include "LPR.h"
#include "OCREngine.h"
#include "Auxiliary.h"

#include <cv.h>
#include <highgui.h>
#include <string>
using std::string;
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <fstream>
using std::ifstream;
#include <list>
using std::list;
using std::pair;

int main (int argc, char* argv[]) {
	// change to correct paths:
	string digitdir("data/digits/");
	string testdir("data/");

	// from here, do not touch.
	// -----------------------------------------------------------------

	OCREngine::instance()->init(digitdir);

	assert(testdir.at(testdir.size() - 1) == '/'); // assert the dir we got ends with a '/'
	ifstream index;
	index.open((testdir + "index").c_str());
	assert(index); // else no database
	typedef pair<string, unsigned long> testentry_t;
	list< testentry_t > tests; // each entry holds an image filename and the correct answer (real license plate number)
	string img_file, img_meaning;
	while (getline(index, img_file, ':') && getline(index, img_meaning))
		tests.push_back( testentry_t(testdir + img_file, Auxiliary::fromString<unsigned long>(img_meaning)) );
	index.close();

	int failed(0);

	string mywin("main window");
	for (list<testentry_t>::iterator it = tests.begin() ; it != tests.end() ; ++it) {
		string myimg(it->first);

		IplImage* myplate = cvLoadImage(myimg.c_str(), -1);
#ifdef _DEBUG
		cvNamedWindow(mywin.c_str(), CV_WINDOW_AUTOSIZE);
		cvShowImage(mywin.c_str(), myplate);
#endif

		LPR plate(myplate);

		cout << "Test: " << it->first << ", expected: " << it->second << ", recieved: " << plate.result() <<
			( it->second == plate.result() ? ". Status: PASSED!" : ". Status: FAILED!" ) << endl;

		if (plate.result() != it->second)
			++failed;

#ifdef _DEBUG
		cvWaitKey();
#endif
		
		cvReleaseImage(&myplate);
		cvDestroyAllWindows();

	}

	return failed;
}

